#!/usr/bin/env python3
# coding=utf-8

""" 
功能:
    实现输入w,s,a,d命令控制底盘移动
"""

import sys
import tty
import termios
import select

class Noblock_terminal:
    def __init__(self):
        fd = sys.stdin.fileno()
        self.old_settings = termios.tcgetattr(fd)
        tty.setraw(sys.stdin.fileno(), termios.TCSANOW)

    def __exit__(self):
        if self.old_settings:
            self.stop_no_block()

    def noblock_get_cmd(self):
        ch = sys.stdin.read(1)
        # sys.stdout.write(ch)
        return ch

    def select_cmd(self, timeout=0.2):
        read_list = [sys.stdin]
        cmd = "0"
        read_ret, write_ret, err_ret = select.select(read_list, [], [], timeout)
        if read_ret:
            for fd in read_ret:
                if fd == sys.stdin:
                    cmd = sys.stdin.read(1)
                else:
                    print("unknow fd")
        else:
            # print("read timeout")
            pass

        return cmd

    def stop_no_block(self):
        fd = sys.stdin.fileno()
        termios.tcsetattr(fd, termios.TCSADRAIN, self.old_settings)
        self.old_settings = None


if __name__ == "__main__":
    noblock = Noblock_terminal()
    while True:
        cmd = noblock.noblock_get_cmd()
        print(cmd)
        if cmd == "q":
            break
    noblock.stop_no_block()